<template>
	<el-dialog title="角色权限设置" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
		<el-tabs tab-position="top">
			<el-tab-pane label="菜单权限">
				<div class="treeMain">
					<el-tree ref="menu" node-key="id" :data="menu.list" :props="menu.props" @check-change="handleCheckChange"  show-checkbox  :default-expanded-keys="[60]"></el-tree>
				</div>
			</el-tab-pane>
		</el-tabs>
		<template #footer>
			<el-button @click="visible=false" >取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>
	export default {
		emits: ['success', 'closed'],
		data() {
			return {
				visible: false,
				isSaveing: false,
				menu: {
					list: [],
					checked: [],
					props: {
						label: (data)=>{
							return data.meta.title
						}
					}
				},
				data: {
					dataType :"1",
					list: [],
					checked: [],
					props: {},
					rule: "",
					form: {}
				},
			}
		},
		mounted() {
			this.getMenu()
		},
		methods: {
			open(){
				this.visible = true;
				return this;
			},
			async submit(){
				this.isSaveing = true;
				//选中的和半选的合并后传值接口
				var menuIds = this.$refs.menu.getCheckedKeys().concat(this.$refs.menu.getHalfCheckedKeys())
				let form = this.form
				let setInfo = await this.$API.common.setUserRoleKey.post({
					roleId : form.id,
					menuIds
				});
				if(setInfo.code == 0) {
					this.isSaveing = false;
					this.visible = false;
					this.$message.success("操作成功")
					this.$emit('success')
				}


			},
			async getMenu(){
				var res = await this.$API.auth.getNavMenu.get({
					sysType: 1
				});
				if(res.code == 0) {
					this.menu.list = res.data
					//获取接口返回的之前选中的和半选的合并，处理过滤掉有叶子节点的key
					this.$refs.menu.setCheckedKeys([])
					let form = this.form
					let checkedArr = form.menuIds || []
					this.$nextTick(() => {
						const that = this
						checkedArr.forEach((i, n) => {
            const node = that.$refs.menu.getNode(i)
							if (node.isLeaf) {
								that.$refs.menu.setChecked(node, true)
							}
						})
					})
				}
			},
			handleCheckChange() {   // tree勾选的方法
				// 勾选的key
				const checkedKeys = this.$refs.menu.getCheckedKeys()
				// 暂选状态的母tab的key
				const halfKeys = this.$refs.menu.getHalfCheckedKeys()
				// 合并两个数组
				const save = checkedKeys.concat(halfKeys)
				this.$emit('allSelectedKeys', save)
			},
			//表单注入数据
			setData(data){
				this.form = data
			}
		}
	}
</script>

<style scoped>
	.treeMain {height:280px;overflow: auto;border: 1px solid #dcdfe6;margin-bottom: 10px;}
</style>
